#include<iostream>
#include<unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<cstring>
#define N 2
#define NUM 1024
using namespace std;
void Write(int wfd)
{
    string s="hello linux";
    char buffer[NUM]={0};
    pid_t self=getpid();
    int count=0;
    while(true)
    {
        buffer[0]=0;
        snprintf(buffer,sizeof(buffer),"%s-%d-%d\n",s.c_str(),self,count++);
        write(wfd,buffer,strlen(buffer));
        //cout<<buffer;
        sleep(1);
    }
}


void Read(int wfd)
{
    char buffer[NUM];
    pid_t self=getpid();
    //int count=0;
    while(true)
    {
        buffer[0]=0;
        size_t n=read(wfd,buffer,sizeof(buffer));
        if(n>0)
        {
            cout<<"father get message["<<self<<"]#"<<buffer;

        }
       
    }
}
int main()
{
    int pipefd[N];
    int n=pipe(pipefd);
    if(n==-1)
    return -1;
    pid_t id=fork();
    if(id<0)
    return -2;
    if(id==0)
    {
        //子进程————来写
        close(pipefd[0]);//关闭读端
        Write(pipefd[1]);
        exit(0);

    }
    else if(id>0)
    {
        //父进程————来读
        close(pipefd[1]);//关闭写端
        Read(pipefd[0]);
        pid_t rid=waitpid(id,nullptr,0);
        if(rid<0)
        return -3;


    }


    return 0;

}